package com.bz.sunmipay.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.bz.sunmipay.model.PaymentDetail;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 收藏数据库
 * <p>
 * Created by liuyakui on 2019/12/9.
 */
public class PaymentDetailDatabase {
    public DBHelper helper;

    public PaymentDetailDatabase(Context context) {
        helper = new DBHelper(context);
    }

    public void deleteById(String id, String tableName) {
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase();
            db.delete(tableName, DBHelper.Column.PAYMENT_ID + "=?", new String[]{id});
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    public boolean insert(PaymentDetail paymentDetail, String tableName) {
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase();
            long rowId = db.insert(tableName, null, getContentValues(paymentDetail));
            if (rowId == -1) {
                return false;
            }
        } catch (Exception e) {
            return false;
        } finally {
            if (db != null) {
                db.close();
            }
        }
        return true;
    }

    public void update(PaymentDetail paymentDetail, String tableName) {
        SQLiteDatabase db = null;
        try {
            db = helper.getWritableDatabase();
            db.update(tableName, getContentValues(paymentDetail), DBHelper.Column.PAYMENT_ID + "=?",
                    new String[]{String.valueOf(paymentDetail.paymentId)});
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    public List<PaymentDetail> queryAll(String tableName) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        ArrayList<PaymentDetail> channelItems = new ArrayList<>();
        try {
            //SQLiteDatabaseLockedException: database is locked (code 5): , while compiling: PRAGMA journal_mode
            db = helper.getReadableDatabase();
            cursor = db.query(tableName, null, null, null, null, null,
                    DBHelper.Column.PAYMENT_DATE + " DESC, " + DBHelper.Column.PAYMENT_DATE + " DESC");
            while (cursor.moveToNext()) {
                channelItems.add(searchData(cursor));
            }
        } catch (Exception e) {
            channelItems = null;
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return channelItems;
    }

    public List<PaymentDetail> queryAllByUserName(String tableName, String userName) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        ArrayList<PaymentDetail> channelItems = new ArrayList<>();
        final String[] selectionArgs = new String[]{userName};
        try {
            //SQLiteDatabaseLockedException: database is locked (code 5): , while compiling: PRAGMA journal_mode
            db = helper.getReadableDatabase();
            cursor = db.query(tableName, null, DBHelper.Column.USER_NAME + "=?", selectionArgs, null, null,
                    DBHelper.Column.PAYMENT_DATE + " DESC, " + DBHelper.Column.PAYMENT_DATE + " DESC");
            while (cursor.moveToNext()) {
                channelItems.add(searchData(cursor));
            }
        } catch (Exception e) {
            channelItems = null;
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return channelItems;
    }

    //查找
    public PaymentDetail queryById(String id) {
        /**
         * 如果内存不足，是不可以在添加数据的，但是却可以读取
         * getWritableDatabase()方法，是在内存不足是，会出异常，不再返回数据库操作实例
         *
         * getReadableDatabase()方法内部，首先试着调用getWritableDatabase()方法取得数据库操作实例
         */
        SQLiteDatabase db = null;
        Cursor cursor = null;
        PaymentDetail channelItem = null;
        final String where = DBHelper.Column.PAYMENT_ID + "=?";
        final String[] selectionArgs = new String[]{id};
        try {
            db = helper.getReadableDatabase();
            cursor = db.query(DBHelper.TABLE_NAME, getColumns(), where, selectionArgs, null, null, null);
            if (cursor.moveToFirst()) {
                channelItem = searchData(cursor);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return channelItem;
    }

    public ContentValues getContentValues(PaymentDetail article) {
        final ContentValues contentValues = new ContentValues();
        contentValues.put(DBHelper.Column.PAYMENT_ID, article.paymentId);//支付订单唯一标识
        contentValues.put(DBHelper.Column.USER_ID, article.userId);
        contentValues.put(DBHelper.Column.PAYMENT_AMOUNT, article.amount);
        contentValues.put(DBHelper.Column.PAYMENT_DATE, String.valueOf(System.currentTimeMillis()));
        contentValues.put(DBHelper.Column.PAYMENT_TYPE, article.paymentType);
        contentValues.put(DBHelper.Column.USER_NAME, article.userName);
        contentValues.put(DBHelper.Column.PAYMENT_RESULT, article.paymentResult);
        return contentValues;
    }

    private PaymentDetail searchData(Cursor cursor) {//查询
        final String userId = cursor.getString(cursor.getColumnIndex(DBHelper.Column.USER_ID));
        final String date = cursor.getString(cursor.getColumnIndex(DBHelper.Column.PAYMENT_DATE));
        final String paymentType = cursor.getString(cursor.getColumnIndex(DBHelper.Column.PAYMENT_TYPE));
        final String userName = cursor.getString(cursor.getColumnIndex(DBHelper.Column.USER_NAME));
        final String amount = cursor.getString(cursor.getColumnIndex(DBHelper.Column.PAYMENT_AMOUNT));
        final String result = cursor.getString(cursor.getColumnIndex(DBHelper.Column.PAYMENT_RESULT));

        final PaymentDetail article = new PaymentDetail();
        article.userId = userId;
        article.paymentType = paymentType;
        article.date = date;
        article.userName = userName;
        article.amount = amount;
        article.paymentResult = result;
        return article;
    }

    public long getCount(String tableName) {
        final SQLiteDatabase db = helper.getReadableDatabase();
        final Cursor cursor = db.rawQuery("select count(*) from " + tableName, null);
        cursor.moveToFirst();
        final long result = cursor.getLong(0);
        cursor.close();
        return result;
    }

    /**
     * 清空表数据
     *
     * @return
     */
    public void clear() {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.delete(DBHelper.TABLE_NAME, null, null);
        db.close();
    }

    public String[] getColumns() {//所有列
        return new String[]{
                DBHelper.Column.USER_ID,
                DBHelper.Column.PAYMENT_ID,
                DBHelper.Column.PAYMENT_DATE,
                DBHelper.Column.PAYMENT_AMOUNT,
                DBHelper.Column.PAYMENT_TYPE,
                DBHelper.Column.PAYMENT_RESULT,
                DBHelper.Column.USER_NAME};
    }
}
